import { Converter, ConvertOptions, ConvertResult } from '../types';
import { CsvConverter } from './csvConverter';

export class ConverterManager {
  private static converters: Map<string, Converter> = new Map();

  // 初始化默认转换器
  static initialize(): void {
    // 注册CSV到XLSX转换器
    this.registerConverter({
      name: 'csv-to-xlsx',
      supportedFormats: ['csv'],
      convert: async (input: string, options: ConvertOptions) => {
        return await CsvConverter.convertToXlsx(input, options);
      },
      validate: (input: string) => {
        return CsvConverter.validateCsv(input);
      }
    });

    // 这里可以注册更多的转换器
    // this.registerConverter({...});
  }

  // 注册转换器
  static registerConverter(converter: Converter): void {
    this.converters.set(converter.name, converter);
  }

  // 获取转换器
  static getConverter(name: string): Converter | undefined {
    return this.converters.get(name);
  }

  // 获取所有转换器
  static getAllConverters(): Converter[] {
    return Array.from(this.converters.values());
  }

  // 根据文件扩展名获取支持的转换器
  static getConvertersForFormat(fileExtension: string): Converter[] {
    return this.getAllConverters().filter(converter =>
      converter.supportedFormats.includes(fileExtension.toLowerCase())
    );
  }

  // 执行转换
  static async convert(
    converterName: string,
    input: any,
    options: ConvertOptions
  ): Promise<ConvertResult> {
    const converter = this.getConverter(converterName);
    if (!converter) {
      return {
        success: false,
        error: `转换器未找到: ${converterName}`
      };
    }

    try {
      // 验证输入
      if (converter.validate && !converter.validate(input)) {
        return {
          success: false,
          error: '输入格式验证失败'
        };
      }

      // 执行转换
      const result = await converter.convert(input, options);
      return {
        success: true,
        data: result
      };

    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '转换过程中发生未知错误'
      };
    }
  }

  // 批量转换
  static async batchConvert(
    converterName: string,
    inputs: any[],
    options: ConvertOptions
  ): Promise<ConvertResult[]> {
    const results: ConvertResult[] = [];

    for (const input of inputs) {
      const result = await this.convert(converterName, input, options);
      results.push(result);
    }

    return results;
  }

  // 获取转换器信息
  static getConverterInfo(name: string): { name: string; supportedFormats: string[] } | null {
    const converter = this.getConverter(name);
    if (!converter) return null;

    return {
      name: converter.name,
      supportedFormats: converter.supportedFormats
    };
  }

  // 检查转换器是否支持特定格式
  static supportsFormat(converterName: string, format: string): boolean {
    const converter = this.getConverter(converterName);
    if (!converter) return false;

    return converter.supportedFormats.includes(format.toLowerCase());
  }

  // 动态加载转换器（为扩展性设计）
  static async loadExternalConverter(converterPath: string): Promise<boolean> {
    try {
      // 这里可以实现动态加载外部转换器模块
      // 例如从配置文件或插件目录加载
      console.log(`加载外部转换器: ${converterPath}`);
      return true;
    } catch (error) {
      console.error('加载外部转换器失败:', error);
      return false;
    }
  }

  // 卸载转换器
  static unregisterConverter(name: string): boolean {
    return this.converters.delete(name);
  }

  // 清空所有转换器
  static clearConverters(): void {
    this.converters.clear();
  }

  // 获取转换器数量
  static getConverterCount(): number {
    return this.converters.size;
  }
}

// 初始化转换器管理器
ConverterManager.initialize();